﻿using System;
using Interfaces.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation;

namespace Framework.Validation
{
    public class GenericValidator : IValidator
    {
        public IValidationResult Validate(object entity, string rulesetName)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");
            
            if (rulesetName == null)
                throw new ArgumentNullException("rulesetName");

            var v = CreateValidator(entity.GetType(), rulesetName);
            
            var result = v.Validate(entity);

            if (result.IsValid)
            {
                v = CreateValidator(entity.GetType());
                result = v.Validate(entity);
            }

            return ValidationResultsConverter.Convert(result, entity);
        }

        public IValidationResult Validate(object entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            var v = CreateValidator(entity.GetType());
            var result = v.Validate(entity);
            return ValidationResultsConverter.Convert(result, entity);
        }

        public IValidationResult ValidateForRuleset(object entity, string rulesetName)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            if (rulesetName == null)
                throw new ArgumentNullException("rulesetName");

            var v = CreateValidator(entity.GetType(), rulesetName);

            var result = v.Validate(entity);

            return ValidationResultsConverter.Convert(result, entity);
        }

        private static Validator CreateValidator(Type entityType, string rulesetName = null)
        {
            return rulesetName != null 
                ? ValidationFactory.CreateValidator(entityType, rulesetName) 
                : ValidationFactory.CreateValidator(entityType);
        }
    }
}
